'use strict';

app.controller('cmdbCtrl', ["$rootScope", "$scope", "$state", "$timeout", "$interval", 'i18nService', "SweetAlert", "uiGridConstants", "uiGridGroupingConstants", "Restangular", "api_bpm_domain", function($rootScope, $scope, $state, $timeout, $interval, i18nService, SweetAlert, uiGridConstants, uiGridGroupingConstants, Restangular, api_bpm_domain) {
    var pdKey = $state.current.pdKey;
    $scope.langs = i18nService.getAllLangs();
    $scope.lang = 'zh-cn';
    i18nService.setCurrentLang($scope.lang);
    $scope.allright = false;
    $scope.someright = true;
    for (var obj in $rootScope.user.role) {
        if ($rootScope.user.role[obj].rolecode == 'configure manager') {
            $scope.allright = true;
            $scope.someright = false;
        }
    }
    $scope.gridOptions = {};
    $scope.gridOptions.data = 'myData';
    $scope.gridOptions.enableColumnResizing = true;
    $scope.gridOptions.enableFiltering = true;
    $scope.gridOptions.enableGridMenu = true;
    $scope.gridOptions.enableRowSelection = true;
    $scope.gridOptions.showGridFooter = true;
    $scope.gridOptions.showColumnFooter = true;
    $scope.gridOptions.fastWatch = true;
    $scope.gridOptions.useExternalPagination = true;
    $scope.gridOptions.paginationPageSizes = [10];
    $scope.gridOptions.paginationPageSize = 10;
    $scope.gridOptions.multiSelect = false;

    $scope.gridOptions.rowTemplate = "<div ng-dblclick=\"grid.appScope.pdList.onDblClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" ui-grid-one-bind-id-grid=\"rowRenderIndex + '-' + col.uid + '-cell'\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" role=\"{{col.isRowHeader ? 'rowheader' : 'gridcell'}}\" ui-grid-cell></div>";

    $scope.gridOptions.rowIdentity = function(row) {
        return row.id;
    };
    $scope.gridOptions.getRowIdentity = function(row) {
        return row.id;
    };

    //  '<a class="btn btn-sm btn-warning" ng-click="grid.appScope.pdList.removeRowFunction(row.entity)">' + '<i class="fa fa-trash"/></a>'
    $scope.gridOptions.columnDefs = [
        { name: '操作', cellTemplate: '<cmdbcpertor item="row.entity" colobject="col">', width: 100, enableFiltering: false },
        { name: 'configuresign', displayName: '配置流水号', width: 140, enableFiltering: false },
        { name: 'configureName', displayName: '配置标题', width: 140 },
        { name: 'initUser.name', displayName: '创建人', width: 100, enableFiltering: false },
        { name: 'registrationTime', displayName: '登记时间', width: 100, enableFiltering: false },
        { name: 'configureClassfy.name', displayName: '配置分类', width: 100, enableFiltering: false },
        { name: 'configureStage.name', displayName: '状态', width: 100, enableFiltering: false }
        // { name: '操作', cellTemplate: '<cmdbcpertor item="row.entity" colobject="col">', width: 100, enableFiltering: false }
    ];
    //     cellTemplate:'<a class="btn btn-sm btn-info" ' +
    //         'ng-click="grid.appScope.pdList.selectRowFunction(row.entity)">' +
    //         '<i class="fa fa-pencil-square-o"/></a>' , enableFiltering:false}
    // ];

    // $scope.gridOptions.importerDataAddCallback = function( grid, newObjects ) {
    //   $scope.myData = $scope.myData.concat( newObjects );
    //     console.log($scope);
    // };

    $scope.refresh = function(style, filterData) {
        var filtersData = {
            "assignee": $rootScope.user.id,
            "candidateGroups": $rootScope.user.group[0].id,
            idx: 0,
            sum: 10
        };
        $scope.gridOptions.refresh();
        $scope.refreshData('expand-right', filtersData);
    };

    $scope.gridOptions.onRegisterApi = function(gridApi) {
        $scope.gridApi = gridApi;
        gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
            // console.log(newPage);
            // console.log(pageSize);
            $rootScope['idx'] = newPage;
            $scope.refreshData('expand-right', { "assignee": $rootScope.user.id, "idx": newPage - 1, "sum": pageSize });
        });

        gridApi.selection.on.rowSelectionChanged($scope, function(data) {
            //$scope.selected.item = data.entity;
            console.log(data);
        });
    };
    // $scope.gridOptions.appScopeProvider = { 
    //         onDblClick : function(row) {
    //             $state.go('app.form.detail',{data:row, formKey:'changeDetail', pdKey:'change'});
    //             //var url = '//google.com';
    //             //$window.open(url, "_blank", "height=600,width=800,toolbar=no,location=no,menubar=no,titlebar=no");
    //         }
    // };

    $scope.selectRowFunction = function(data) {
        console.log(data);
        //    $state.go('app.process.modeler',{modelId:data.id});
        $state.go('app.cmdb.modeler', { taskId: data.taskId, processInstanceId: data.processInstanceId });
    };
    $scope.lookfunction = function(data) {
        $state.go('app.detail', { formKey: 'cmdbDetail', pdKey: 'configure', dataId: data.id, processInstanceId: data.processInstanceId });
    };
    $scope.onDblClick = function(row) {
        $state.go('app.detail', { formKey: 'cmdbDetail', pdKey: 'configure', dataId: row.entity.id, taskId: row.entity.taskId, processInstanceId: row.entity.processInstanceId });
    };
    /*
      appScopeProvider: { 
          onDblClick : function(row) {
             var url = '//google.com';
             $window.open(url, "_blank", "height=600,width=800,toolbar=no,location=no,menubar=no,titlebar=no");
           }
      },
      rowTemplate: "<div ng-dblclick=\"grid.appScope.onDblClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" ui-grid-cell ></div>"

     */


    this.removeRowFunction = function(data) {
        //TODO $translate('key')
        SweetAlert.swal({
            title: "确认删除?",
            text: "删除以后，你将不能恢复该数据!",
            type: "warning",
            cancelButtonText: "取消",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认删除!"
        }, function(isConfirm) {
            if (isConfirm) {
                // api_bpm_domain.removemodel(data.id).then(function(response){
                //   if(response){
                //     $scope.refreshData();
                //     SweetAlert.swal({
                //       title: "删除成功!",
                //       confirmButtonColor: "#007AFF"
                //     });
                //   }
                // });
            } else {

            }
        });

    }


    //$scope.callsPending = 0;
    //var i = 0;
    var defaultFilterData = {
        "assignee": $rootScope.user.id,
        "idx": 0,
        "sum": 10,
    };
    if (angular.isDefined($rootScope.search) && angular.isDefined($rootScope.search.cmdb)) {
        defaultFilterData['searchType'] = $rootScope.search.cmdb;
        $scope.searchTypes = $rootScope.search.cmdb;
    }
    if ($rootScope['cmdbs'] != 'cmdb') { $rootScope.idx = 1 }
    if (angular.isDefined($rootScope.idx) && $rootScope.cmdbs != "false") {
        $rootScope['cmdbs'] = 'cmdb';
        defaultFilterData.idx = $rootScope.idx - 1;
    } else { $rootScope.cmdbs = ""; }
    $scope.ldloading = {};
    $scope.refreshData = function(style, filterData) {
        $scope.ldloading[style.replace('-', '_')] = true;
        console.log($scope.ldloading.expand_right)
        if (angular.isUndefined(filterData)) {
            defaultFilterData.idx = $rootScope.idx - 1;
            filterData = defaultFilterData;
        }
        if (angular.isDefined($scope.searchTypes)) {
            $rootScope['search'] = {};
            filterData['searchType'] = $scope.searchTypes;
            $rootScope['search']['cmdb'] = $scope.searchTypes;
        }
        $scope.myData = [];
        //var start = new Date();
        //var sec = $interval(function () {
        //$scope.callsPending++;
        api_bpm_domain.fetchtask(pdKey, filterData).then(function(data) {
            $scope.callsPending--;
            var myData = Restangular.stripRestangular(data);
            $scope.gridOptions.totalItems = myData.resultCount;
            $scope.myData = myData.data;
            $scope.ldloading[style.replace('-', '_')] = false;
        }, function() {
            $scope.ldloading[style.replace('-', '_')] = false;
        });
        //}, 200, 1);

        // var timeout = $timeout(function() {
        //    $interval.cancel(sec);
        //    $scope.left = '';
        // }, 2000);

        // $scope.$on('$destroy', function(){
        //   $timeout.cancel(timeout);
        //   $interval.cancel(sec);
        // });
    };

    $scope.refreshData('expand-right', defaultFilterData);
}]);
app.controller('CmdbOperCtrl', ['$rootScope', '$http', '$scope', function($rootScope, $http, $scope, $event) {
    // console.log($scope.item);
    if ($scope.item.handlerUser != null) {

        if ($rootScope.user.id == $scope.item.handlerUser.id) {
            $scope.item.chaozuoPower = true;

        }
    }


    $scope.view = function() {
        $scope.colobject.grid.appScope.lookfunction($scope.item);
    }
    $scope.edit = function() {
        $scope.colobject.grid.appScope.selectRowFunction($scope.item);
        // $scope.doEdit($scope.item.id);
    }


}]);

app.directive('cmdbcpertor', function() {
    return {
        restrict: 'E',
        scope: {
            item: '=',
            colobject: '='
        },
        controller: 'CmdbOperCtrl',
        template: '<div class="links cl-effect-1">' +
            '<a ng-click="view()"   tooltip="查看" tooltip-placement="left"><i class="ti-eye"></i></a>' +
            '<a ng-click="edit()"  ng-show="{{item.chaozuoPower}}" tooltip="编辑" tooltip-placement="left"><i class="fa fa-pencil-square-o"></i></a>' +
            '</div>'
    };
});